
var bg = chrome.extension.getBackgroundPage();
var getItemkey = bg.getItemkey
var updateUnread = bg.updateUnread

// bg.allData bg.focusData bg.allReaded  由于这些参数都是对象,所以这边是赋值的指针,指向同一个对象
// var bg.allData = bg.bg.allData;               // 所有数据
// var bg.focusData = bg.bg.focusData;           // 关注股票的数据
// var bg.allReaded = bg.bg.allReaded;           // 已读
// console.log("getBackgroundPage",bg,bg.allReaded)



// 初始化页面
bg.updatePopPage()
    // {
    //     url: "http://push2ex.eastmoney.com/getAllStockChanges?type=8201,8202,8193,4,32,64,8207,8209,8211,8213,8215,8204,8203,8194,8,16,128,8208,8210,8212,8214,8216&cb=jQuery35102755143189102953_1650598496290&ut=7eea3edcaed734bea9cbfc24409ed989&dpt=wzchanges&_=1650598496311&pageindex=0&pagesize=1000",
    //     dataType: "jsonp", //指定服务器返回的数据类型
    //     jsonp:"jQuery35102755143189102953_1650598496290"
    // },function(res){
    //     console.log('bgGetUnusualList res',res);
    
    // }

// $.ajax({
//     url: "http://push2ex.eastmoney.com/getAllStockChanges?type=8201,8202,8193,4,32,64,8207,8209,8211,8213,8215,8204,8203,8194,8,16,128,8208,8210,8212,8214,8216&cb=jQuery35102755143189102953_1650598496290&ut=7eea3edcaed734bea9cbfc24409ed989&dpt=wzchanges&_=1650598496311"
//     +"&pageindex=0&pagesize=1000",
//     dataType: "jsonp", //指定服务器返回的数据类型
//     jsonp:"jQuery35102755143189102953_1650598496290"
// }).done(function(res){
//     console.log('res',res);

// }).fail(function(){

// });


/**   数据处理  */
// 自定义够造key
// function getItemkey(item){
//     return item.t + '_' + item.tm+ '_' + item.c;
// }
function getTime( stime , steplen ) {
    var time = stime.toString()
    time = time.length==5 ? '0'+time : time;
    var step = steplen ? steplen: 2 , string  = time.toString();
    let r = [];
    for(let i = 0, len = string.length; i < len; i=i+step) {
        // console.log("i",i, i+step,string)
        r.push( string.substr( i , step ) )
    }
    // console.log("r",r , time )
    return r.join(":");
}

function getBoardLot( stockhands ){
    var num = parseInt(stockhands)/100
    if(num>10000){
        return (num/10000).toFixed(2) + "万手";
    }else{
        return num + "手";
    }
}


function getDescription( obj ){
    switch( obj.t ){
        case 8201:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8202:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8193:  return getBoardLot(obj.i);
        case 4:     return ( parseFloat(obj.i) ).toFixed(2) + "元";
        case 32:    return ( parseFloat(obj.i) ).toFixed(2) + "元";
        case 64:    return getBoardLot(obj.i);
        case 8207:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8209:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8211:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8213:  return ( parseFloat(obj.i) ).toFixed(2) + "元";
        case 8215:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        
        case 8204:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8203:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8194:  return getBoardLot(obj.i);
        case 8:     return ( parseFloat(obj.i) ).toFixed(2) + "元";
        case 16:    return ( parseFloat(obj.i) ).toFixed(2) + "元";
        case 128:   return getBoardLot(obj.i);
        case 8208:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8210:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8212:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
        case 8214:  return ( parseFloat(obj.i) ).toFixed(2) + "元";
        case 8216:  return (parseFloat(obj.i) * 100).toFixed(2) + "%";
    }
}

//  数据渲染方式 tClassify
function listItem( item ){
    if(item){
        return `<div class="list_item color_`+classifyColor[item.t]+`" data-item=`+JSON.stringify(item)+`>`+
        `<div class="item_unit item_unit_wid60">${ getTime(item.tm) }</div>`+
        `<div class="item_unit item_unit_wid80 item_unit_stock">${ item.n }</div>`+
        `<div class="item_unit item_unit_wid100">${ tClassify[item.t] }</div>`+
        `<div class="item_unit item_unit_wid60">${ getDescription( item ) }</div>`+
        `<div class="item_unit item_unit_flex1">${ getDays20info( item ) }</div>`+
        // `<div class="item_unit">${ item.premium_rt }%</div>`+
        `</div>`;
    }else{
        return  '<div class="list_header list_item"><div class="item_unit item_unit_wid60">异动时间</div>'+
            '<div class="item_unit item_unit_wid80">股票名称</div>'+
            '<div class="item_unit item_unit_wid100">类型</div>'+
            '<div class="item_unit item_unit_wid60">相关信息</div>'+
            '<div class="item_unit item_unit_flex1">涨20%价格(20日)</div>'+
            // '<div class="item_unit">溢价率</div>'+
        '</div>';
    }
}

function getSearchOptions(list){
    let oriCodes = [];
    let arr = [];
    for( var m = 0 ; m<list.length ; m++ ){
        let c = list[m].c;
        if( oriCodes.indexOf(c) == -1 ){
            oriCodes.push( c );
            var tsArr = list.filter( item => c === item.c )
            var tList = tsArr.map(item=>item.t);
            arr.push({
                c: list[m].c,
                n: list[m].n,
                lastItem:tsArr[0],
                t: tList,
                ts:tList.length,
                pc:tList.filter( item => positiveClassify.indexOf(item)>-1 ),
                nc:tList.filter( item => negativeClassify.indexOf(item)>-1 ),
            })
        }
    }
    console.log("arr getSearchOptions",arr)
    arr.sort( (a1,a2) => a2.ts-a1.ts );
    let OptionsHtml = [`<option value="">直接选择或搜索选择</option>`]
    for( let n = 0 ; n< arr.length ; n++ ){
        let t=  arr[n].lastItem.t ? arr[n].lastItem.t : undefined
        let lastClassifyType = (t && (t===4 || t===8)) ? `【${ getTime(arr[n].lastItem.tm) } ${tClassify[t].substr(1,2)}】` : `【${ getTime(arr[n].lastItem.tm) }】`;
        OptionsHtml.push(
            `<option value="${ arr[n].c }">${ arr[n].n } (${ arr[n].ts }[<span class="i_color_red"> ${ arr[n].pc.length }</span>/`+
            `<span class="i_color_green"> ${ arr[n].nc.length }</span>])【${ ( 100 * arr[n].pc.length/arr[n].ts ).toFixed( 2 ) }%】${lastClassifyType}</option>`
        )
    }
    return OptionsHtml;
}
// tab 是 select 的 lay-filter的值
function customRend( arr , tab ){
    if(arr){
        var type = (tab!='3') ? 'baseRend' : 'focusRend'
        // console.log(" customRend select值" , $(`select[lay-filter='${ tab }']`) )
        var c = $(`select[lay-filter='${ tab }']`) ? $(`select[lay-filter='${ tab }']`).attr( 'data-value') : '';
        // console.log( "customRend" , tab , c )
        var list = c ?arr.filter(item=> c==item.c ) : arr 
        var rendFunc = null;
        switch(type){
            case 'baseRend':
                rendFunc = listItem;
                break;
            case 'baseRend':
                rendFunc = listItem;
                break;
            default:
                rendFunc = focusListItem;
                break;
        }
        var htmlList = [ ]
        for(var m=0;m<list.length;m++){
            htmlList.push( rendFunc(list[m]) )
        }
        return htmlList;
    }
    return []
}
function dataRendList( arr ){
    var list = arr ? arr : bg.allFilData;
    // var htmlList = [ ]
    // for(var m=0;m<list.length;m++){
    //     htmlList.push( listItem(list[m]) )
    // }
    // console.log( "dataRendList" ,bg.allFilData, htmlList )
    $("#container .content .header").html(listItem() )
    $("#container .search .stock_search").html( getSearchOptions(list).join('') )
    $("#container .content .table").html( customRend( list , '0' ).join('') )

    // $("#container_focus .content .header").html( focusListItem() )
    // $("#container_focus .content .table").html( htmlList.join('') )
    var subscribeFilData = ( bg.subscribeFilData ) ? bg.subscribeFilData : [];
    // for(var m=0;m<subscribeFilData.length;m++){
    //     subscribeFilDataHtmlList.push( listItem( subscribeFilData[m] ) )
    // }
    // console.log( "dataRendList subscribeFilData" ,bg.allFilData, subscribeFilDataHtmlList )
    $("#container2 .content .header").html( listItem() )
    $("#container2 .search .stock_search").html( getSearchOptions(subscribeFilData).join('') )
    $("#container2 .content .table").html( customRend( subscribeFilData , '1' ).join('') )


    var followData = ( bg.followData )? bg.followData : [];
    // var followDataHtmlList = [ ]
    // for(var m=0;m<followData.length;m++){
    //     followDataHtmlList.push( listItem( followData[m] ) )
    // }
    // console.log( "dataRendList" ,bg.allFilData, followDataHtmlList )
    $("#container3 .content .header").html( listItem() )
    $("#container3 .search .stock_search").html( getSearchOptions( followData ).join('') )
    $("#container3 .content .table").html( customRend( followData , '2' ).join('') )
}
function getDays20info(obj){
    if( obj.low20Rise){
        return obj.low20Rise.toFixed(2) + '('+ ( obj.maxRise ? ( obj.maxRise ).toFixed(2) : '-' ) +'%)' 
    }else{
        return '-'
    }
}
function focusListItem( item ){
    if(item){
        var focusItemClass  = item.readed ? '' : 'focus_item'
        return `<div class="focus_message `+ focusItemClass +` list_item color_`+classifyColor[item.t]+`" data-id=`+item.tm+"_"+ item.t+` data-item=`+JSON.stringify(item)+`>`+
        `<div class="item_unit item_unit_wid60">${ getTime(item.tm) }</div>`+
        `<div class="item_unit item_unit_wid80 item_unit_stock">${ item.n }</div>`+
        `<div class="item_unit item_unit_wid100">${ tClassify[item.t] }</div>`+
        `<div class="item_unit item_unit_wid60">${ getDescription( item ) }</div>`+
        `<div class="item_unit item_unit_flex1">${ getDays20info( item ) }</div>`+
        // `<div class="item_unit">${ item.premium_rt }%</div>`+
        `</div>`;
    }else{
        return  '<div class="list_header list_item">'+
            '<div class="item_unit item_unit_wid60">异动时间</div>'+
            '<div class="item_unit item_unit_wid80">股票名称</div>'+
            '<div class="item_unit item_unit_wid100">类型</div>'+
            '<div class="item_unit item_unit_wid60">相关信息</div>'+
            '<div class="item_unit item_unit_flex1">近20日涨幅20%价格</div>'+
            // '<div class="item_unit">正股价格</div>'+
            // '<div class="item_unit">溢价率</div>'+
        '</div>';
    }
}

function focusRendList( arr ){
    var list = arr ? arr : bg.focusData
    // var htmlList = []
    // for(var m=0;m<list.length;m++){
    //     htmlList.push( focusListItem(list[m]) )
    // }
    $("#container_focus .content .header").html( focusListItem() )
    $("#container_focus .search .stock_search").html( getSearchOptions(list).join('') )
    $("#container_focus .content .table").html(  customRend( list , '3' ).join('') )
}

// 监听
console.log("focus_message绑定")
$(document).on("click",".focus_message",function(e){
    console.log("动态绑定",e)
    console.log( "动态绑定值" , $(e.currentTarget).attr("data-item") )
    var data = JSON.parse( $(e.currentTarget).attr("data-item") )
    bg.focusData.map(function(item,index){
        if(data.tm === item.tm && data.t === item.t ){
            bg.focusData[index].readed = true                      // 已读
            console.log("focus_message",bg.allReaded)
            bg.allReaded[getItemkey(item)] = true                 // 存入已读对象
            $(e.currentTarget).removeClass("focus_item")
        }
    })
    // console.log("bg.focusData",bg.focusData,bg.focusData.filter( function(item){
    //     return !item.readed
    // }).length )
    updateUnread()
});
$(document).on("click",".item_unit_stock",function(e){
    var dataDOM = $(e.currentTarget).parent('.list_item')[0]
    // console.log("item_unit_stock", $(dataDOM) )
    // console.log( "item_unit_stock" , $(dataDOM).attr("data-item") )
    var data = JSON.parse( $(dataDOM).attr("data-item") )
    bg.toStockDetail( data );
    updateUnread()
});

$(document).on("click","#to_setting",function(){
    tOptions()
})

// 跳转 Options 页面
function tOptions(){
    console.log("跳转 chrome options")
    chrome.tabs.create({ url: "pages/options.html" });
}
// console.log("focusTypeValue",focusTypeValue , defaultFocusType , defaultFocusType.toString())
var layer = layui.layer,
    table = layui.table;
    form = layui.form;
// 监听 selelct 选择事件
form.on('select', function(data){
    // console.log(" 下拉 selece 监听" , data );
    // console.log(" 下拉 selece 监听" , $(data.elem).attr("lay-filter") ); //得到select原始DOM对象
    var tab = $(data.elem).attr("lay-filter");
    var c = data.value;
  
    // 存储 选中值
    $(`select[lay-filter='${ tab }']`).attr( 'data-value' , c )
    // select 组件赋值,便于后面的取出
    switch(tab){
        case '0':
            $("#container .content .table").html( customRend( bg.allFilData , tab ) )
            break;
        case '1':
            // console.log("formonselect 1" , c ,  customRend( c ? bg.subscribeFilData.filter(item=> c==item.c ) : bg.subscribeFilData , tab ).join('') )
            $("#container2 .content .table").html( customRend( bg.subscribeFilData , tab ) )
            break;
        case '2':
            $("#container3 .content .table").html( customRend( bg.followData , tab ) )
            break;
        case '3':
            $("#container_focus .content .table").html( customRend( bg.focusData , tab ) )
            break;
        default:
            $("#container .content .table").html( customRend( bg.allFilData , tab ) )
            break;
    }
    // console.log("render 赋值", $(`select[lay-filter='${ tab }']`) , $(`select[lay-filter='${ tab }']`).eq(0))

    // console.log(data.value); //得到被选中的值
    // console.log(data.othis); //得到美化后的DOM对象
});      